#!/usr/bin/env python 
# coding:utf-8
# @Time :9/11/18 11:22

import time

from common.mongo import MongDb
from common.time_human import TimeHuman
from config.mongo_conf import MONGO_DB_SOURCE
from scheduler.schedule_conf_loader import ScheduleConfLoader
from config.schedule_conf import SCHEDULE_CONF


class SchedulerManage(object):

    # 调度器更新周期
    __INIT_SCHEDULER_PERIOD = 60

    def __init__(self, config_path="config/schedule_table_list.conf", log=None):
        self.logger = log

        self.__is_running = True

        self.time_human = TimeHuman()

        self.__last_init_time = self.time_human.now()

        # 配置数据库
        self.__source_db = MongDb(MONGO_DB_SOURCE['host'], MONGO_DB_SOURCE['port'], MONGO_DB_SOURCE['db'],
                                  MONGO_DB_SOURCE['username'],
                                  MONGO_DB_SOURCE['password'], log=lo)


        # 配置加载器
        self.__conf_loader = ScheduleConfLoader(SCHEDULE_CONF["schedule_table_name"],
                                                self.__source_db,
                                                config_path,
                                                self.logger)

        # 调度缓存
        self.__schedule_cache_redis = None

        # 消息队列，获取所有的tube
        self.__beanstalk_handler = None

        # 清理数据线程
        self.__clear_handler = None

        # 清空调度缓存

        self.logger.info("初始化裁判文书调度完成...")

    # 定时初始化调度程序
    def __init_scheduler_timing(self):
        current_time = self.time_human.now()
        if current_time - self.__last_init_time >= self.__INIT_SCHEDULER_PERIOD:
            self.__init_scheduler()
            self.__last_init_time = current_time
            self.logger.info("周期性巡视调度情况...")

    # 初始化调度器
    def __init_scheduler(self):
        # 加载配置项
        table_config_dict = self.__conf_loader.get_config_dict()

    # 判断是否在调度中
    def __is_scheduing(self):
        pass

    # 调度请求页面
    def __schedule_request(self):
        pass

    # 调度
    def __schedule(self):
        pass

    def start(self):
        while self.__is_running:
            try:
                # 周期性初始化调度器
                self.__init_scheduler_timing()

                # 调度
                if not self.__schedule():
                    time.sleep(1)

            except Exception as why:
                self.logger.error("调度任务异常，原因是={}".format(why))
                time.sleep(60)

    def stop(self):
        self.__is_running = False


